from threading import Thread
import os, serial, paramiko, time
from kthread import KThread
from time import sleep

class Buffers(KThread):
    def __init__(self, saida, funcao, arquivo, hasbuffer, sleeptime):
        self.saida = saida
        self.executar = True
        self.readfunction = funcao
        self.gravar = True
        self.arquivo = open(arquivo, "a")
        self.poetime = True
        self.hasbuffer = hasbuffer
        self.sleeptime = sleeptime
        KThread.__init__(self)
        self.start()

    def __del__(self):
        if self.gravar:
            self.arquivo.close()

    def setGravar(self, gravar, arquivo):
        self.gravar = gravar
        self.arquivo = arquivo
        self.arquivo = open(arquivo, "a")
		
    def trocaTimestamp(self):
        self.poetime = not self.poetime
        
    def run(self):
        while self.executar:
            sleep(self.sleeptime)
            while bool(self.hasbuffer()):
                try:
                    str = self.readfunction(self.hasbuffer())
                except:
                    str = ''
                    
                if len(str):
                    hora = time.strftime('[%H:%M:%S]')
                    if self.poetime:
                        str = str.replace('\n','\n'+hora)
                    txt = str.replace('\r','')
                    self.arquivo.write(txt)
                    self.arquivo.flush()
                    self.saida(txt.replace(chr(00),''))
